# BigData course project
# Serial version of training algorithm for SOM
# Main module (plotter)
#
# Arguments:
#
# <class_file>: output of the classify.py program, containing one
# R^2 coordinate per line, where line number is assumed to be train vector
# position in trainset.
#
# <preclass_file>: pre-classification of train vectors, assuming index to
# be train vector position in trainset; and the last field in the line
# to be an string representing the category code (space as separator)
#
# <colormap_file>: mapping of category codes into colors, using names
# understood my pylab. each line has two columnes (space as separator), first 
# column contains the category code and second one contaings color name/code
#
# <plot_file>: output file to be generated (png), where each coordinate in the 
# <class_file> is draw using color associated to pre-classification.
#

import sys
from pylab import *
from util import *

if len(sys.argv) != 5:
    log("Passed %d args\n", len(sys.argv))
    log("Usage: %s <class_file> <pre_class> <color_map> <plot_file>", sys.argv[0])
    sys.exit(1)

class_file = sys.argv[1]
preclass_file = sys.argv[2]
colormap_file = sys.argv[3]
plot_file = sys.argv[4]

make_coord = lambda l: tuple(map(int, l.split()))
# ignore the neuron index of classification file
_, x, y = zip(*map(make_coord, read_all_lines(class_file)))

get_class = lambda l: l.split()[-1]
preclass = map(get_class, read_all_lines(preclass_file))

get_cmap = lambda l: tuple(l.split())
colormap = dict(map(get_cmap, read_all_lines(colormap_file)))

def get_color(cl):
    try:
        c = colormap[cl]
    except KeyError:
        c = colormap["DEF"]
    return c
colors = map(get_color, preclass)

fig = figure(1)
ax = fig.add_subplot(111, axisbg="black")
ax.scatter(x, y, s=1, color=colors)
fig.canvas.draw()
savefig(plot_file, bbox_inches="tight")
